#!/usr/bin/python

import os
import sys
import random

text = ''
textlist = []
node = []		# node list
nint = []
link = []		# link list
lnode1 = [] 	# one end node of link			- index as link list
lnode2 = [] 	# the other end node of link	- index as link list

MAXINT = 4

# delete node info for output ns file - used in agglink
def aggnsdeletenode(x):
	global textlist
	a = 0
	for i in range(len(textlist)):
		if textlist[i].find('[$ns node]') > -1:
			a = i
			break
	textlist.pop(a+x)

# delete link info for output ns file - used in agglink
def aggnsdeletelink(x):
	global textlist
	a = 0
	for i in range(len(textlist)):
		if textlist[i].find('set Link') > -1:
			a = i
			break
	textlist.pop(a+x)

try:
  file_object = open(sys.argv[1])
  all_the_text = file_object.read()
except:
	sys.exit("Too few arguments. Use ./input_int_limit.py filename.ns")
else:
	file_object.close()
	
# Read each line into textlist:
for x in all_the_text:
	if x != '\n':
		text = text + x
	else:
		text = text + '\n'
		textlist.append(text)
		text = ''
	
# Extract the node related info
for y in textlist:
  if y.find('[$ns node]') > -1:
    node.append(y[y.index(' ')+1:y.index('[$ns node]')-1])
    nint.append(0)

# Extract the link related info
for y in textlist:
	if y[0:8] == 'set Link':
		link.append(y[y.index('$')+1:len(y)])  # Record link summary
		k1 = link[-1].index('$')
		k2 = link[-1].index(' ', k1)
		lnode1.append(link[-1][k1+1:k2])	# Record one end node
		nint[node.index(lnode1[-1])] = nint[node.index(lnode1[-1])] + 1
		k3 = link[-1].index(' ', k2+1)
		lnode2.append(link[-1][k2+2:k3])	# Record another end node
		nint[node.index(lnode2[-1])] = nint[node.index(lnode2[-1])] + 1

linknummax = len(link)

# Ensure the maximum interface does not exceed MAXINT	
while max(nint) > MAXINT:
	ndi = nint.index(max(nint))	# index of one end of deleting link
	delnode1 = node[ndi]			# one end of deleting link
	maxint = 0
	i = 0
	ldi = 0
	while 1:
		try:
			i = lnode1.index(delnode1, i+1)
			if nint[node.index(lnode2[i])] > maxint:
				maxint = nint[node.index(lnode2[i])]
				delnode2 = lnode2[i]
				ldi = i					# index of deleting link
		except:
			break
	i = 0
	while 1:
		try:
			i = lnode2.index(delnode1, i+1)
			if nint[node.index(lnode1[i])] > maxint:
				maxint = nint[node.index(lnode1[i])]
				delnode2 = lnode1[i]
				ldi = i
		except:
			break
	link.pop(ldi)
	lnode1.pop(ldi)
	lnode2.pop(ldi)
	aggnsdeletelink(ldi)
	nint[node.index(delnode1)] = nint[node.index(delnode1)] - 1
	nint[node.index(delnode2)] = nint[node.index(delnode2)] - 1
"""
# Delete all the nodes with 0 interface
while min(nint) == 0:
	ndi = nint.index(min(nint))	# index of deleting node
	aggnsdeletenode(ndi)
	node.pop(ndi)
	nint.pop(ndi)
"""

k = 0
while min(nint) < 2:
	tempint = list(nint)
	mdi1 = tempint.index(min(tempint))
	tempint[mdi1] = 1000000
	while 1:
		mdi2 = tempint.index(min(tempint))
		if node[mdi1] > node[mdi2]:
			newlink = node[mdi1] + '+' + node[mdi2]
		else:
			newlink = node[mdi2] + '+' + node[mdi1]
		linkend = []
		for k in range(len(link)):
			if lnode1[k] > lnode2[k]:
				linkend.append(lnode1[k])
				linkend[k] = linkend[k] + '+' + lnode2[k]
			else:
				linkend.append(lnode2[k])
				linkend[k] = linkend[k] + '+' + lnode1[k]
		if linkend.count(newlink) == 0:
			break
		else:
			tempint[mdi2] = 1000000
	newline = 'set Link' + str(linknummax+k) + ' [$ns duplex-link $' +\
	node[mdi1] + ' $' + node[mdi2] + ' ' + str(100*(random.randint(1,1)))\
	+ 'Mb ' + str(random.randint(2,4)) + 'ms DropTail]\n'	
	i = textlist.index('### Links that require multiplexing\n');
	link.append(newline)
	lnode1.append(node[mdi1])
	lnode2.append(node[mdi2])
	nint[node.index(node[mdi1])] = nint[node.index(node[mdi1])] + 1
	nint[node.index(node[mdi2])] = nint[node.index(node[mdi2])] + 1
	textlist.insert(i-1, newline)
	k = k + 1

print len(node)
	
# Output file for ns
file_object=open(sys.argv[1][0:sys.argv[1].find('.ns')]+'1.ns','w')
file_object.writelines(textlist)
file_object.close( )

os.system('ns ' +sys.argv[1][0:sys.argv[1].find('.ns')]+ '1.ns')
os.system("nam out.nam")

